<?php

namespace app\api\controller;

use app\common\controller\ApiController;
use app\common\model\Artifact;
use app\common\model\User;
use app\common\model\Work as WorkModel;
use think\Db;
use think\Env;
use think\Request;

/**
 * 作品接口
 */
class Work extends ApiController
{
    protected $noNeedLogin = ['index', 'detail', 'save', 'audioStatusUpdate', 'videoStatusUpdate'];
    protected $noNeedRight = '*';
    protected $tableName = 'work';
    protected $fields = false;
    protected $fieldsExcept = false;
    protected $onlySelf = false;
    protected $orderBy = 'id desc';
    protected $conditions = [];
    protected $defaultPageSize = 10;

    protected function processData($method, $data)
    {
        if ($method === 'beforeList') {
            // 精选10条
            $this->conditions['is_featured'] = 1;
        }
        if ($method === 'afterList') {
            // 添加 image_url
            $artifactModel = new Artifact();    
            $artifact = $artifactModel->getAllArtifact($this->getRedis());
            
            // 修复：使用 array_walk 或 array_map 替代 each() 方法
            $data = collection($data)->each(function ($item) use ($artifact) {
                // 如果 $item['artifact_id'] 为空，则 image_url 也设置为空
                $item['image_url'] = !empty($item['artifact_id']) && isset($artifact[$item['artifact_id']]) ? $artifact[$item['artifact_id']]['image_url'] : '';
                return $item;
            });
        }
        return $data;
    }

    protected function paging()
    {
        $page = $this->request->param('page', 1);
        $pageSize = $this->request->param('pageSize', $this->defaultPageSize ?? 10);
        $pageSize = $pageSize > 100 ? 100 : $pageSize;
        $offset = ($page - 1) * $pageSize;
        return [$offset, $pageSize];
    }

    /**
     * 获取当前用户作品5条
     */
    public function me()
    {
        $this->conditions = [];
        $this->conditions['user_id'] = $this->auth->id;
        $offset = 0;
        $limit = 5;
        $data = WorkModel::where($this->conditions)
            ->order($this->orderBy)
            ->limit($offset, $limit)->select();
        $artifactModel = new Artifact();    
        $artifact = $artifactModel->getAllArtifact($this->getRedis());
        
        // 修复：使用 array_walk 或 array_map 替代 each() 方法
        $data = collection($data)->each(function ($item) use ($artifact) {
            // 如果 $item['artifact_id'] 为空，则 image_url 也设置为空
            if (!empty($item['artifact_id']) && isset($artifact[$item['artifact_id']])) {
                $item['image_url'] = $artifact[$item['artifact_id']]['image_url'];
            } else {
                $item['image_url'] = '';
            }
            return $item;
        });
        return $this->success('获取成功', $data);
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $this->conditions = [];
        $data = $this->buildQuery()->find($id);
        if (!$data) {
            $this->fail('No data is avaliable', 404);
        }
        $artifactId = $data['artifact_id'];
        if ($artifactId) {
            $artifact = Artifact::get($artifactId);
            if ($artifact) {
                $data['image_url'] = $artifact['image_url'];
            }
        }
        return $this->res($data);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = $this->request->param('', null, $this->paramFilter);
        // 验证签名
        $userId = $data['user_id'];
        $this->checkSign($request, $userId);
        $user = User::get($userId);


        Db::startTrans();

        try {
            // 添加文物朝代
            $artifactId = $data['artifact_id'];
            if ($artifactId) {
                $artifact = Artifact::get($artifactId);
                if ($artifact) {
                    $data['title'] = $artifact['name'];
                    $data['dynasty'] = $artifact['dynasty'];
                }
            }
            $data['nickname'] = $user['nickname'];
            $data['createtime'] = time();
            $data = $this->processData('beforeSave', $data);
        } catch (\think\exception\ErrorException $e) {
            $msg = $e->getMessage();
            $file = $e->getFile();
            $line = $e->getLine();
            trace("msg: $msg | file: $file | line: $line", 'error');
            Db::rollback();
            $this->fail(__('Failed to update data'));
        }

        if ($this->onlySelf) {
            $user = $this->auth->getUser();
            $data['user_id'] = $user->id;
        }

        try {
            $id = Db::name($this->tableName)->insertGetId($data);
            if (!$id) {
                $this->fail(__('Failed to update data'));
            }
            $data['id'] = $id;
            $data = $this->processData('afterSave', $data);
            Db::commit();
        } catch (\think\exception\ErrorException $e) {
            $msg = $e->getMessage();
            $file = $e->getFile();
            $line = $e->getLine();
            Db::rollback();
            trace("msg: $msg | file: $file | line: $line", 'error');
            $this->fail(__('Failed to update data'));
        } catch (\think\Exception $e) {
            $msg = $e->getMessage();
            trace("msg: $msg", 'error');
            Db::rollback();
            $this->fail(__('Failed to update data'));
        }

        return $this->success('', $data);
    }

    private function checkSign($request, $userId)
    {
        $key = Env::get('api.signature_key');
        if (!$userId) {
            $this->fail(__('user_id is missing'));
        }
        if (!$key) {
            $this->fail(__('Signature key is missing'));
        }
        $sign = md5($key . $userId);
        // 从header中的signature获取签名
        $signature = $request->header('signature');
        if (!$signature) {
            $this->fail(__('header signature is missing'));
        }
        if ($signature !== $sign) {
            $this->fail(__('Signature verification failed'));
        }
    }

    /**
     * 音频状态更新
     */
    public function audioStatusUpdate(Request $request)
    {
        $data = $this->request->param('', null, $this->paramFilter);
        // $data 中只保留id ,user_id 和 audio_status
        $data = array_intersect_key($data, ['id' => '', 'user_id' => '', 'audio_status' => '']);
        // 验证签名
        $userId = $data['user_id'];
        $audioStatus = $data['audio_status'];
        $this->checkSign($request, $userId);
        $id = $data['id'];
        if (!$id) {
            $this->fail(__('id is missing'));
        }
        $this->conditions = [];
        $row = $this->buildQuery()->find($id);
        if (!$row) {
            $this->fail('No data is avaliable', 404);
        }
        if ($audioStatus == $row['audio_status']) {
            return $this->success('', $data);
        }
        if ($audioStatus == 1) {
            // 将id加入合成音乐背景的redis队列
            $redis = $this->getRedis();
            $redis->handler()->lPush('tbbs_audio_queue', $id);
        }

        WorkModel::update(['audio_status' => $audioStatus], ['id' => $id]);
        return $this->success('', $data);
    }

    /**
     * 视频状态更新
     */
    public function videoStatusUpdate(Request $request)
    {
        $data = $this->request->param('', null, $this->paramFilter);
        // $data 中只保留id 和 video_status
        $data = array_intersect_key($data, ['id' => '', 'video_status' => '']);
        $videoStatus = $data['video_status'];
        $id = $data['id'];
        if (!$id) {
            $this->fail(__('id is missing'));
        }
        $this->conditions = [];
        $row = $this->buildQuery()->find($id);
        if (!$row) {
            $this->fail('No data is avaliable', 404);
        }
        if ($videoStatus == $row['video_status']) {
            return $this->success('', $data);
        }
        if ($videoStatus == 1) {
            // 将id加入合成视频的redis队列
            $redis = $this->getRedis();
            $redis->handler()->lPush('tbbs_video_queue', $id);
        }

        WorkModel::update(['video_status' => $videoStatus], ['id' => $id]);
        return $this->success('', $data);
    }

    
}
